import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:xiongan_app_yy/utils/device_utils.dart';

import '../dialog.dart';

class ScanWidget extends StatefulWidget {
  final ValueChanged<String> clickCallback;

  @override
  State<StatefulWidget> createState() {
    return _ScanState();
  }

  ScanWidget({@required this.clickCallback});
}

class _ScanState extends State<ScanWidget> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Icon(IconData(
        0xe68b,
        fontFamily: "wuIconFont",
      )),
      onTap: () {
        String str = DeviceUtils.androidInfo.model;
        if (str == "S917") {
          getScanResult().then((str) {
            widget.clickCallback(str);
          });
        } else {
          scan().then((str) {
            widget.clickCallback(str);
          });
        }
      },
    );
  }

  //  扫描二维码
  Future<String> scan() async {
    // 此处为扫码结果，barcode为二维码的内容
    // String barcode = await BarcodeScanner.scan();
    if (await checkPermission(context)) {
      String barcode = await platform.invokeMethod('scanCode');
      print('扫码结果: ' + barcode);
      return barcode;
    } else {
      return "";
    }
  }

  Future<bool> checkPermission(BuildContext context) async {
    PermissionStatus status =
        await PermissionHandler().checkPermissionStatus(PermissionGroup.camera);
    if (status != PermissionStatus.granted) {
      var map = await PermissionHandler()
          .requestPermissions([PermissionGroup.camera]);
      if (map[PermissionGroup.camera] != PermissionStatus.granted) {
        bool dialogChoice = await showDeleteConfirmDialog1(
            context, "权限申请", "需要打开摄像头，否则无法扫描", "取消", "去设置");
        if (dialogChoice == null) {
          return false;
        } else {
          bool isShown = await PermissionHandler()
              .shouldShowRequestPermissionRationale(PermissionGroup.camera);
          if (isShown) {
            checkPermission(context);
          } else {
            return await PermissionHandler().openAppSettings();
          }
        }
      } else {
        return true;
      }
    } else {
      return true;
    }
  }

  static const platform = const MethodChannel('com.example.xiongan_app_yy');

  //红外线扫描
  Future<String> getScanResult() async {
    try {
      String result = await platform.invokeMethod('scan');
      print('扫码结果: ' + result);
      return result;
    } on PlatformException catch (e) {
      print(e.toString());
      return "";
    }
  }
}
